﻿using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using MouseExtender.Logic;
using MouseExtender.Logic.Entities;
using MouseExtender.Logic.Helpers;
using MouseExtender.Logic.Managers;
using MouseExtender.Resources;
using ImageControl = System.Windows.Controls.Image;

namespace MouseExtender.Controls.UserControls
{
    /// <summary>
    /// Interaction logic for EditItemUC.xaml
    /// </summary>
    public partial class EditItemUC : UserControl
    {
        private static readonly string _fileLabel = UIResources.EditItem_File;
        private static readonly string _urlLabel = UIResources.EditItem_Url;

        private int _selectedIconIndex = -1;
        /// <summary>
        /// Stores reference to original bitmap for Reset functionality
        /// </summary>
        private BitmapSource _originalIcon = null;
        private string _originalLocation = null;

        public string LaunchPath
        {
            get;
            set;
        }

        public LauncherItem Item
        {
            get;
            private set;
        }

        public EditItemUC(LauncherItem item)
        {
            InitializeComponent();
            SetContextAndVisibility(item);
        }

        public void SetItem(LauncherItem item)
        {
            SetContextAndVisibility(item);
        }

        private void SetContextAndVisibility(LauncherItem item)
        {
            DataContext = Item = item;
            if (Item.IsUrl)
            {
                lblArguments.Visibility =
                txtArguments.Visibility =
                lblDirectory.Visibility =
                txtDirectory.Visibility =
                expander.Visibility = Visibility.Collapsed;
            }
            else
            {
                lblArguments.Visibility =
                txtArguments.Visibility =
                lblDirectory.Visibility =
                txtDirectory.Visibility =
                expander.Visibility = Visibility.Visible;
                LoadIcons();
            }
            _originalLocation = Item.LaunchPath;
        }

        /// <summary>
        /// Fills listbox with icons from file
        /// </summary>
        private void LoadIcons()
        {
            IconHelper.LoadIcons(lbAvailableIcons, Item);
        }

        public void ApplySetting()
        {
            //not url
            if (!Item.IsUrl)
            {
                string fullPath = Win32Helper.FindInPath(txtFile.Text);
                if (Item.LaunchPath != _originalLocation)
                {
                    ReloadIcons();
                    _selectedIconIndex = 0;
                }
                Item.LaunchPath = txtFile.Text;
                Item.Arguments = txtArguments.Text;
                Item.WorkingDirectory = txtDirectory.Text;
            }
            //url
            else
            {
                Item.LaunchPath = MainWindow.NormalizeUrl(txtFile.Text);
            }

            //common part
            Item.ToolTip = txtToolTip.Text;
            Item.IconIndex = _selectedIconIndex;
            Item.ItemColor = Constants.Defaults.ItemColor;

            SettingsManager.CurrentSettings.SettingChanged();

            if (Item.IsUrl)
            {
                ThreadPool.QueueUserWorkItem(IconHelper.ExtractFavoriteIcon, Item);
            }
        }

        /// <summary>
        /// Sets icon for expander header in order not to load icon twice 
        /// </summary>
        /// <param name="bitmapSource">The icon bitmap source</param>
        public void SetIcon(BitmapSource bitmapSource)
        {
            expander.Header = bitmapSource;
            _originalIcon = bitmapSource;
        }

        #region Event Handers

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            lblFileUrl.Text = Item.IsUrl ? _urlLabel : _fileLabel;
            txtFile.Focus();
        }

        /// <summary>
        /// Collapse expander on clicking cancer or okay
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">EventArgs</param>
        private void AnyButton_Click(object sender, RoutedEventArgs e)
        {
            expander.IsExpanded = false;
        }

        private void lbIconsItem_DoubleClick(object sender, MouseEventArgs e)
        {
            if (lbAvailableIcons.SelectedItems.Count == 1)
            {
                _selectedIconIndex = lbAvailableIcons.SelectedIndex;
                expander.Header = (lbAvailableIcons.SelectedItem as ImageControl).Source;
            }
        }

        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = Constants.FileFilters.IconFilter;
            if (!string.IsNullOrEmpty(Item.IconSource))
            {
                string iconSourceFullName = PathHelper.GetFullPath(Item.IconSource);
                ofd.InitialDirectory = System.IO.Path.GetDirectoryName(iconSourceFullName);
            }
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string relPath = PathHelper.RelativeToAppBaseFolderPath(ofd.FileName);
                txtFileName.Text = relPath;
                Item.IconSource = relPath;
                LoadIcons();
            }
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            ReloadIcons();
            expander.Header = _originalIcon;
        }

        private void ReloadIcons()
        {
            Item.IconSource = null;
            txtFileName.Text = Item.IconSource;
            LoadIcons();
        }
        #endregion
    }
}
